/**
 * Created by nico on 2016/2/26.
 */

//任务首页
app.controller('SellsHomeCtrl',['$scope','$state','$stateParams','BaseFactory','$User','$rootScope','$cordovaBarcodeScanner',
    function($scope,$state,$stateParams,BaseFactory,$User,$rootScope,$cordovaBarcodeScanner){

        //下拉刷新
        $scope.doRefresh = function(){
            $scope.init() ;
        };
        var uid = $User.get('id') ;
        $scope.MarketTypes = [] ;
        $scope.loadFinish={flag:false};
        $scope.init =function(){
            //获取任务首页的各个分类的数量
            BaseFactory.sellsHome().then(function(data){
                $scope.loadFinish.flag=true;
                var temp = [] ;
                var temp2 = [] ;
                for(var i in data){
                    temp.push(data[i]);
                    if(parseInt(i%2)===1){
                        temp2.push(temp);
                        temp = [] ;
                    }
                    if(parseInt(i) === parseInt(data.length-1)){
                        console.log(data.length)
                        temp2.push(temp);
                    }
                }
                $scope.MarketTypes = temp2 ;
            }).catch(function(err){
                console.log(err)
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }
        //展示首页
        $scope.init();
        //搜索
        $scope.searchGood=function(search){
            $state.go('tab.goodslist',{search:search,type:""})
        }
        $scope.marketType=function(type){
            $state.go('tab.goodslist',{search:"",type:parseInt(type)})
        }
        $scope.goToCart = function(){
            $state.go('marketOrders') ;
        }
    }
]);
app.controller('GoodsListCtrl', ['$scope','$state','$stateParams','$filter','$User','BaseFactory',
    function($scope, $state,$stateParams,$filter,$User,BaseFactory) {
    var search = $stateParams.search;
    var type = $stateParams.type;

    var uid=$User.get('id') ;
    $scope.search={searchInput:"",marketType:0};
    $scope.address={};
    $scope.goodsList = [] ;
        //下拉刷新
        $scope.doRefresh = function(){
            $scope.init(search,type) ;
        };
    /**
     *商品列表
     * @param search 搜索内容
     **/

    $scope.init = function(search,type){
        console.log();
        BaseFactory.sellProList(search,type).then(function(data){
            $scope.goodsList=data;
        }).finally(function(){
            $scope.$broadcast('scroll.refreshComplete');
        });
    }
    $scope.init(search,type);
    /**
     * 选择规格
     * @param ind
     * @param good
     * @param pec
     */
    $scope.selectSpec=function(ind,good,pec){
        alert(pec.id);
        console.log(pec)
        angular.forEach($scope.goodsList,function(data,index,array){
            if($scope.goodsList[index].id==good.id){
                if(good.productType!=3){
                    console.log($scope.goodsList[index]);
                    $scope.goodsList[index]["minPrice"] = pec.grprice;
                }
                $scope.goodsList[index]["minSpec"] = pec.id;
            }
        })
    }
    /**
     *pre下单函数
     * @param ind 索引值
     * @param good 商品对象
     */
    $scope.createOrder=function(ind,good){
        if(!good.minSpec){
            good.minSpec = good.spec[0].id ;
        }
        //加入购物车
        BaseFactory.addToCart(uid,good.id,good.minSpec,1,good.productType).then(function(data){
            if(data.code === 0){
                alert('添加成功');
            }else{
                alert('添加失败');
            }
        }).catch(function(err){
            console.log(err)
            alert('添加失败');
        });
    };

    $scope.goToCart = function(){
        $state.go('marketOrders') ;
    };


}]);
app.controller('MarketOrderCtrl', ['$scope','$state','$stateParams','$filter','$User','BaseFactory','$cordovaBarcodeScanner','$rootScope',
    function($scope, $state,$stateParams,$filter,$User,BaseFactory,$cordovaBarcodeScanner,$rootScope) {
        $rootScope.$on('$stateChangeStart', function(event,toState,fromState){
            if(toState.name === 'marketOrders'){
                $scope.init() ;
            }
        });
        var uid=$User.get('id') ;
        //下拉刷新
        $scope.doRefresh = function(){
            $scope.init() ;
        };

        $scope.canAccount = 0 ;
        $scope.product={allAmount: 0,packageprice:0,orderAddress:''};
        /**
         *商品列表
         * @param search 搜索内容
         **/
        $scope.init = function(){
            var allAmount = 0 ;
            var packageprice = 0 ;
            BaseFactory.getCourerCart(uid).then(function(data){
                $scope.cartlist=data;
                for(var i in data){
                    allAmount = parseFloat(allAmount) + parseFloat(data[i].info.grprice)* parseInt(data[i].number);
                    packageprice = parseFloat(packageprice) + parseFloat(data[i].info.packageprice)*parseInt(data[i].number);
                }
                $scope.product={allAmount: allAmount,packageprice:packageprice};
                if( $scope.product.packageprice>=10){
                    $scope.canAccount = 1 ;
                }
            }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
            });
        }
        $scope.init();
        $scope.minus=function(index,good){
            $scope.canAccount = 0 ;
            if(!good.number){
                good.number = 0
            }
            if(good.info.inventory < 1){
                good.number = 0;
            }else{
                var mini = 1;
                var old = good.number ;
                good.number = (parseInt(good.number) > mini)?(parseInt(good.number)-1):mini;
                var newM = good.number ;
                $scope.product.allAmount = $scope.product.allAmount-parseFloat(good.info.grprice)*(old-newM);
                $scope.product.packageprice = $scope.product.packageprice-parseFloat(good.info.packageprice)*(old-newM);
                if($scope.product.allAmount >= 10){
                    $scope.canAccount = 1 ;
                }else{
                    $scope.canAccount = 0 ;
                }
            }
        };
        /**
         *  增加购买数量
         */
        $scope.plus = function(index,good){
            $scope.canAccount = 0 ;
            if(!good.number){
                good.number = 0 ;
            }
            if(good.info.inventory < 1){
                good.number=0;
            }else{
                var inventory  = good.info.inventory;
                var size = parseInt(good.number);
                var maxSize = inventory;
                var old = good.number ;
                good.number = (parseInt(size) < maxSize)?(parseInt(size)+1):maxSize;
                var newM = good.number ;
                $scope.product.allAmount = $scope.product.allAmount-parseFloat(good.info.grprice)*(old-newM);
                $scope.product.packageprice = $scope.product.packageprice-parseFloat(good.info.packageprice)*(old-newM);
                if($scope.product.allAmount >= 10){
                    $scope.canAccount = 1 ;
                }else{
                    $scope.canAccount = 0 ;
                }
            }
        };
        //numberChange
        $scope.numberChange = function(index,good){
            $scope.product={allAmount: 0,packageprice:0};
            if(!good.number && good.number >= good.info.inventory ){
                good.number = good.info.inventory ;
            }
            if(good.info.inventory < 1 ){
                good.number = 1 ;
            }
            var allAmount = 0 ;
            var packageprice = 0 ;
            var data = $scope.cartlist ;
            for(var i in data){
                allAmount = parseFloat(allAmount) + parseFloat(data[i].info.grprice)* parseInt(data[i].number);
                packageprice = parseFloat(packageprice) + parseFloat(data[i].info.packageprice)*parseInt(data[i].number);
            }
            $scope.product={allAmount: allAmount||0,packageprice:packageprice||0};
            if( $scope.product.packageprice>=10){
                $scope.canAccount = 1 ;
            }
        }
        //删除某一个商品
        $scope.trashOne=function(index,good){
            BaseFactory.trashCartOne(uid,good.pid).then(function(data){
                console.log(data)
                if(data.code === 0){
                    alert('删除成功');
                    $scope.init();
                }else{
                    alert('删除失败');
                }
            }).catch(function(err){
                console.log(err);
                alert('删除失败');
            });
        };
        //清空购物车
        $scope.trashAll=function(){
            BaseFactory.trashCartAll(uid).then(function(data){
                $state.go('tab.goodsType');
            });
        };

        $scope.amountNow = function(){

            if(!$scope.product.orderAddress || !$scope.product.name || !$scope.product.phone){
                alert("请选择收货信息!");
                return;
            }
            var order = {
                toName:$scope.product.name,
                toPhone:$scope.product.phone,
                toStreet:$scope.product.orderAddress,
                total:parseFloat($scope.product.packageprice),
                remark:$scope.product.remark||"/",
                uid:uid
            };

            BaseFactory.updateCart(uid,$scope.cartlist).then(function(data){
                if(data.fieldCount === 0){
                    BaseFactory.createMarketOrder(order).then(function(data){
                        console.log(data);
                        if(data.errno === 0){
                            //下单成功
                            alert("下单成功，订单号为："+data.data.orderid);
                            $state.go('tab.goodsType');
                        }else{
                            alert("下单失败，请检查网络");
                            $state.go('tab.goodsType');
                        }
                    }).catch(function(err){
                        console.log(err);
                        alert(JSON.stringify(err));
                        //$state.go('tab.goodsType');
                    });
                }else{
                    alert("下单失败，请检查网络");
                    $state.go('tab.goodsType');
                }
            });
        };

        $scope.barscanReceive = function(){
            alert('该功能尚未开放')
        };
        $scope.goBack = function(){
            window.history.back();
        };
    }
]);
